/**
 * Aibton.com Inc.
 * Copyright (c) 2016-2017 All Rights Reserved.
 */
package com.aibton.framework.util;

import java.io.*;

import org.apache.commons.codec.binary.Base64;

/**
 * Base64工具类转换
 * @author huzhihui
 * @version $: v 0.1 2017 2017/7/19 16:31 huzhihui Exp $$
 */
public class Base64FileUtils {

    /**
     * 文件转base64
     * @param file  文件对象
     * @return  Base64字符串
     * @throws Exception    异常信息
     */
    public static String imageFileToBase64(File file) throws Exception {
        byte[] data = null;
        InputStream in = new FileInputStream(file);
        data = new byte[in.available()];
        in.read(data);
        in.close();
        return Base64.encodeBase64String(data);
    }

    /**
     *
     * @param base64String  base64字符串
     * @param fileUrlPre	文件物理路径前缀D:/vieagrfiles
     * @param imageUrl	图片路径 image/201609181474209880226291
     * @return	images/3123131.jpg
     * @throws Exception    异常信息
     */
    public static String base64ToImageFile(String base64String, String fileUrlPre,
                                           String imageUrl) throws Exception {
        if (base64String == null || base64String.length() < 100) {
            return null;
        }
        int endIndex = base64String.indexOf("base64,");
        base64String = base64String.substring(endIndex + 7);
        byte[] bytes = Base64.decodeBase64(base64String);
        for (int i = 0; i < bytes.length; ++i) {
            if (bytes[i] < 0) {// 调整异常数据
                bytes[i] += 256;
            }
        }
        OutputStream out = new FileOutputStream(fileUrlPre + '/' + imageUrl);
        out.write(bytes);
        out.flush();
        out.close();
        return imageUrl;
    }
}
